#!/usr/bin/env bash
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Script for copying of ChromeDriver from local workspace to chromedriver
# bucket.

set -eu

source "$(dirname "$0")/common.sh"
ensure_linux $0
ensure_release_root

version=$(cat ".version")
release_type=$(cat ".type")
src=packed

if [ ! -d "$src" -o ! -f "$src/latest" -o "$version" != "$(cat $src/latest)" ]
then
  echo "Nothing to publish in $0. Command 'nest pack' needs to be executed first!" >&2
  exit 1
fi


## Uncomment this code if you wan't to debug the script without sending anything to the server
#function gsutil {
#  echo "gsutil $@" >&2
#  echo "1.2.4664.45"
#}
#export -f gsutil

gsutil cp $src/chromedriver_linux64.zip gs://chromedriver/$version/chromedriver_linux64.zip
gsutil cp $src/chromedriver_mac64.zip gs://chromedriver/$version/chromedriver_mac64.zip
gsutil cp $src/chromedriver_mac64_m1.zip gs://chromedriver/$version/chromedriver_mac64_m1.zip
gsutil cp $src/chromedriver_win32.zip gs://chromedriver/$version/chromedriver_win32.zip

build=`echo $version | sed -E 's/\.[0-9]+$//'`
major=`echo $version | sed -E 's/\.[0-9.]+$//'`
gsutil -h Content-Type:text/plain cp "$src/latest" gs://chromedriver/LATEST_RELEASE_$build
gsutil -h Content-Type:text/plain cp "$src/latest" gs://chromedriver/LATEST_RELEASE_$major

gsutil cp $src/notes.txt gs://chromedriver/$version/notes.txt

function version_is_less {
  v1="$1"
  v2="$2"
  build1="$(echo "$v1" | cut -f3 -d'.')"
  build2="$(echo "$v2" | cut -f3 -d'.')"
  patch1="${v1##*.}"
  patch2="${v2##*.}"
  if [ "$build1" -lt "$build2" ]
  then
    return 0
  fi
  if [ "$build1" -gt "$build2" ]
  then
    return 1
  fi
  [ "$patch1" -lt "$patch2" ]
}

if [ "$release_type" == 'stable' ]
then
  current_version="$(gsutil cat gs://chromedriver/LATEST_RELEASE)"
  if version_is_less "$current_version" "$version"
  then
    gsutil cp gs://chromedriver/LATEST_RELEASE_$major gs://chromedriver/LATEST_RELEASE
    new_version="$(gsutil cat gs://chromedriver/LATEST_RELEASE)"
    if [ "$new_version" != "$version" ]
    then
      echo "Failed to update LATEST_RELEASE version to $version" >&2
      exit 1
    fi
  fi
fi
